package com.alumni_circle.controller.me;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alumni_circle.core.config.RedisCache;
import com.alumni_circle.core.config.SysLog;
import com.alumni_circle.core.entity.BaseId;
import com.alumni_circle.core.entity.PageBase;
import com.alumni_circle.core.entity.ResponseListModel;
import com.alumni_circle.core.entity.ResponseModel;
import com.alumni_circle.core.utils.GetOpen;
import com.alumni_circle.core.utils.ModelUtils;
import com.alumni_circle.core.utils.Modify;
import com.alumni_circle.core.utils.SecurityUtils;
import com.alumni_circle.core.web.BaseController;
import com.alumni_circle.entity.me.User;
import com.alumni_circle.entity.me.VO.UserSearchVO;
import com.alumni_circle.entity.me.VO.UserUpdateVO;
import com.alumni_circle.entity.me.VO.UserViewVO;
import com.alumni_circle.service.me.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

import java.util.List;

import static com.alumni_circle.core.constant.ResponseCode.INVALID_PARAM;

/**
 * @author 龙小虬
 * @since 2020-07-06 22:58
 */
@Api(tags = "用户管理")
@Controller
@RequestMapping("/user")
public class UserController extends BaseController<User> {

    @Resource
    private IUserService userService;

    @Resource
    RedisCache redisCache;


    /**
     * 增加、更新用户信息
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addUser", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "新增用户信息", notes = "增加用户信息", httpMethod = "POST", response = ResponseModel.class)
    @SysLog(type="增",accessInfo="新增用户信息",url="/user/addUser")
    public ResponseModel addUser(@ApiParam(required = true, name = "user")
                                 @RequestBody User user) {
        String code = user.getOpenid();
        //获取openid
        String openid = GetOpen.sendGet(code);
        if(openid.contains("errcode")){
            return new ResponseModel<>(INVALID_PARAM.getCode(),INVALID_PARAM.getMessage());
        }
        user.setOpenid(openid);
        //取消头像下载，使用微信提供的链接
//        try {
//            if (user.getIcon() != null) {
//                user.setIcon(DownloadPicture.downloadPicture(user.getIcon(), user.getOpenid()));
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid",openid);
        if(ObjectUtil.hasEmpty(userService.getOne(queryWrapper))){
            //保存新用户数据
            userService.save(user);
            redisCache.setCacheObject(code,user);
//            System.out.println((User)redisCache.getCacheObject(key));
        }else {
            userService.update(user,queryWrapper);
            redisCache.setCacheObject(code,user);
        }
        return new ResponseModel<>();
    }

    /**
     * 查询用户信息
     *
     * @param baseId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/selectUser", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询用户信息", notes = "查询用户信息", httpMethod = "POST", response = ResponseModel.class)
    @SysLog(type="查",accessInfo="查询用户信息",url="/user/selectUser")
    public ResponseModel selectUser(@ApiParam(required = true, name = "baseId")
                                    @RequestBody BaseId baseId) {

        return new ResponseModel<>(ModelUtils.transform(userService.getById(SecurityUtils.getId()), UserViewVO.class));
    }


    @ResponseBody
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "更新用户信息", notes = "更新用户信息", httpMethod = "POST", response = ResponseModel.class)
    @SysLog(type="改",accessInfo="更新用户信息",url="/user/updateUser")
    public ResponseModel updateUser(@ApiParam(required = true, name = "userUpdateVO")
                                        @RequestBody UserUpdateVO userUpdateVO) {

        User user = ModelUtils.transform(userUpdateVO,User.class);
        assert user != null;
        if(!StrUtil.hasEmpty(user.getIcon())){
            user.setIcon(Modify.modifyImage(user.getIcon()));
        }
        user.setId(SecurityUtils.getId());
        userService.updateById(user);
        return new ResponseModel<>();
    }

    @ResponseBody
    @RequestMapping(value = "/updateUsers", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "管理员更新用户信息", notes = "管理员更新用户信息", httpMethod = "POST", response = ResponseModel.class)
    @SysLog(type="改",accessInfo="管理员更新用户信息",url="/user/updateUsers")
    public ResponseModel updateUsers(@ApiParam(required = true, name = "userUpdateVO")
                                    @RequestBody UserUpdateVO userUpdateVO) {

        if(StrUtil.hasEmpty(userUpdateVO.getState())){
            userService.updateById(ModelUtils.transform(userUpdateVO,User.class));
        } else {
            userService.updateUser(userUpdateVO.getState(),userUpdateVO.getId());
        }
        return new ResponseModel<>();
    }


    @ResponseBody
    @RequestMapping(value = "/selectUserCode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询用户信息", notes = "查询用户信息", httpMethod = "POST", response = ResponseModel.class)
    @SysLog(type="查",accessInfo="查询用户信息",url="/user/selectUserCode")
    public ResponseModel selectUserCode(@ApiParam(required = true, name = "baseId")
                                        @RequestBody BaseId baseId) {

        String openid = GetOpen.sendGet(baseId.getId());
        User user = userService.getOne(new QueryWrapper<User>().and(warpper -> warpper.like("openid", baseId.getId())));
        return new ResponseModel<>(ModelUtils.transform(user, UserViewVO.class));
    }

    @ResponseBody
    @RequestMapping(value = "/searchUser", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询用户信息", notes = "查询用户信息", httpMethod = "POST", response = ResponseModel.class)
    @SysLog(type="查",accessInfo="查询用户信息",url="/user/searchUser")
    public ResponseListModel searchUser(@ApiParam(required = true, name = "baseId")
                                        @RequestBody UserSearchVO userSearchVO) {

        PageHelper.startPage(userSearchVO.getPageNum(),userSearchVO.getPageSize());
        List<UserUpdateVO>list = userService.searchUser(userSearchVO.getName(),userSearchVO.getUpdateBy(),userSearchVO.getUpdateTime(),userSearchVO.getEmail(),userSearchVO.getPhone(),userSearchVO.getRole());
        PageInfo<UserUpdateVO> pageInfo = new PageInfo<>(list);
        return new ResponseListModel<>(list,String.valueOf(pageInfo.getTotal()));
    }

    @ResponseBody
    @RequestMapping(value = "/deleteUser", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "删除用户信息", notes = "删除用户信息", httpMethod = "POST", response = ResponseModel.class)
    @SysLog(type="删",accessInfo="删除用户信息",url="/user/deleteUser")
    public ResponseModel deleteUser(@ApiParam(required = true, name = "baseId")
                                    @RequestBody BaseId baseId) {

        userService.removeById(baseId.getId());
        return new ResponseModel();
    }

    @ResponseBody
    @RequestMapping(value = "/deleteUsers", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "管理员删除用户信息", notes = "管理员删除用户信息", httpMethod = "POST", response = ResponseModel.class)
    @SysLog(type="删",accessInfo="管理员删除用户信息",url="/user/deleteUsers")
    public ResponseModel deleteUsers(@ApiParam(required = true, name = "baseId")
                                    @RequestBody BaseId baseId) {

        userService.delUser(baseId.getId());
        return new ResponseModel();
    }


    @ResponseBody
    @RequestMapping(value = "/getAllUser", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询符合条件用户信息", notes = "查询符合条件用户信息", httpMethod = "POST", response = ResponseModel.class)
    @SysLog(type="查",accessInfo="查询符合条件用户信息",url="/user/getAllUser")
    public ResponseListModel getAllUser(@ApiParam(required = true, name = "pageBase")
                                        @RequestBody PageBase pageBase) {
        PageHelper.startPage(pageBase.getPageNum(),pageBase.getPageSize());
        return new ResponseListModel<>(userService.list());
    }

    @ResponseBody
    @RequestMapping(value = "/getAllUsers", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询所有条件用户信息（附带角色）", notes = "查询所有条件用户信息（附带角色）", httpMethod = "POST", response = ResponseModel.class)
    @SysLog(type="查",accessInfo="查询所有条件用户信息（附带角色）",url="/user/getAllUsers")
    public ResponseListModel getAllUsers(@ApiParam(required = true, name = "pageBase")
                                        @RequestBody PageBase pageBase) {
        PageHelper.startPage(pageBase.getPageNum(),pageBase.getPageSize());
        List<UserUpdateVO> list = userService.getAllUsers();
        PageInfo<UserUpdateVO> pageInfo = new PageInfo(list);
        return new ResponseListModel<>(list,String.valueOf(pageInfo.getTotal()));
    }

}